package cn.com.saintlee.id;

import cn.com.saintlee.util.SpringUtil;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.util.Assert;


public class IdGeneratorFactory {

    private final static String BEAN_SUFFIX = "IdGenerator";


    public static IdGenerator create(String key) {

        ApplicationContext applicationContext = SpringUtil.getApplicationContext();

        Assert.hasLength(key, "key is null");
        Assert.notNull(applicationContext, "applicationContext is null");
        String beanName = key + BEAN_SUFFIX;
        DynamicIdGenerator idGenerator = null;
        // 判断是否有该beanName
        if (applicationContext.containsBean(beanName)) {
            idGenerator = applicationContext.getBean(beanName, DynamicIdGenerator.class);
        } else {
            //获取BeanFactory
            DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();

            //创建bean信息.
            BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(DynamicIdGenerator.class);

            //获取RedisConnectionFactory
            RedisConnectionFactory redisConnectionFactory = applicationContext.getBean(RedisConnectionFactory.class);

            Assert.notNull(redisConnectionFactory, "redisConnectionFactory is null");

            //注册单例bean
            defaultListableBeanFactory.registerSingleton(beanName, new DynamicIdGenerator(key, redisConnectionFactory));

            idGenerator = applicationContext.getBean(beanName, DynamicIdGenerator.class);
        }

        return idGenerator;
    }
}
